package com.xiaoh.dormitoryrepairreportbackend.utils;

import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.constant.UserConstant;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.GeneralUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Objects;

/**
 * 用户上下文工具类
 */
public class UserHolder {

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static GeneralUser getCurrentUser() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        HttpServletRequest request = attributes.getRequest();
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        GeneralUser currentUser = (GeneralUser) userObj;

        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return currentUser;
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 当前登录用户ID
     */
    public static Long getCurrentUserId() {
        return getCurrentUser().getId();
    }

    /**
     * 检查当前用户是否为管理员
     *
     * @return 是否为管理员
     */
    public static boolean isAdmin() {
        GeneralUser currentUser = getCurrentUser();
        return currentUser.getUserType() != null &&
               currentUser.getUserType() == UserConstant.UserType.ADMIN;
    }

    /**
     * 检查当前用户是否为学生
     *
     * @return 是否为学生
     */
    public static boolean isStudent() {
        GeneralUser currentUser = getCurrentUser();
        return currentUser.getUserType() != null &&
               currentUser.getUserType() == UserConstant.UserType.STUDENT;
    }

    /**
     * 检查当前用户是否为维修工
     *
     * @return 是否为维修工
     */
    public static boolean isMaintenance() {
        GeneralUser currentUser = getCurrentUser();
        return currentUser.getUserType() != null &&
               currentUser.getUserType() == UserConstant.UserType.MAINTENANCE;
    }
}
